package cn.edu.jlu.grid.vjm;

import java.io.IOException;
import java.io.ObjectInputStream;
import java.net.Socket;

public class VJMMessageProcessor implements Runnable {
	private VJMMessage msg = null;
	private Socket connection = null;
	
	public VJMMessageProcessor(Socket conn) {
		connection = conn;
	}
	public VJMMessageProcessor(VJMMessage msg) {
		this.msg = msg;
	}
	
	public void run() {
		if(connection == null) {
			msg.onSend();
		} else {
			// read message from vjob
			try {
				ObjectInputStream oin = new ObjectInputStream(connection.getInputStream());
				Object obj = oin.readObject();
				if(obj instanceof VJMMessage) {
					System.out.println(obj);
					((VJMMessage) obj).onReceive(connection);
				} else {
					// exception
				}
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (ClassNotFoundException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			
		}
		if(connection != null) {
			try { connection.close(); } catch(Exception e) {}
		}
	}
}
